<template>
  <div>
    <BackgroundComponent></BackgroundComponent>
    <div id="logo">zhupp的智能客服</div>
    <div id="login">
      <el-card class="box-card">
        <div id="form">
          <p class="login-title">登录</p>

          <el-input 
            v-model="email" 
            placeholder="请输入邮箱" 
            style="margin-bottom: 10px;" 
            :disabled="isSubmitting"
            :class="{'is-error': emailError}" 
          />
          <div v-if="emailError" class="el-input__error">{{ emailError }}</div>

          <el-input
            placeholder="请输入密码"
            v-model="password"
            show-password
            style="margin-bottom: 10px;"
            :disabled="isSubmitting"
            :class="{'is-error': passwordError}" 
          />
          <div v-if="passwordError" class="el-input__error">{{ passwordError }}</div>

          <el-radio-group v-model="userType" style="margin-bottom: 10px;">
            <el-radio label="user">用户登录</el-radio>
            <el-radio label="admin">管理员登录</el-radio>
          </el-radio-group>

          <el-button
            type="primary"
            @click="login"
            style="width: 100%; margin-top: 10px;"
            :loading="isSubmitting"
            :disabled="isSubmitting"
          >登录</el-button>

          <div style="text-align: center; margin-top: 10px;">
            <span>还没有账号？</span>
            <el-button
              type="text"
              @click="goToRegister"
              style="padding: 0; color: #ff4d4f; font-weight: bold;"
            >去注册</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div id="clock">
      <div id="time">{{ time }}</div>
      <div id="date">{{ date }}</div>
    </div>

    <div id="copyright">Copyright © 2024 zhupp. All Rights Reserved.</div>
  </div>
</template>

<script>
import BackgroundComponent from '@/components/BackgroundComponent.vue';
import axios from 'axios';

export default {
  name: 'LoginView',
  components: {
    BackgroundComponent,
  },
  data() {
    return {
      email: '',
      password: '',
      userType: 'user',  // 默认用户为普通用户
      time: '',
      date: '',
      isSubmitting: false,
      emailError: '',
      passwordError: '',
    };
  },
  mounted() {
    this.updateClock();
    setInterval(this.updateClock, 1000);
  },
  methods: {
    updateClock() {
      const d = new Date();
      const year = d.getFullYear();
      const mon = d.getMonth() + 1;
      const day = d.getDate();
      const hour = d.getHours().toString().padStart(2, '0');
      const minute = d.getMinutes().toString().padStart(2, '0');
      this.time = `${hour}:${minute}`;
      this.date = `${year}/${mon}/${day}`;
    },

    validateEmail() {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zAZ0-9.-]+\.[a-zA-Z]{2,4}$/;
      this.emailError = emailRegex.test(this.email) ? '' : '请输入有效的邮箱地址';
    },

    validatePassword() {
      this.passwordError = this.password.length >= 6 ? '' : '密码至少6个字符';
    },

    login() {
      if (!this.email || !this.password) {
        this.$message.error('请填写邮箱和密码');
        return;
      }

      this.validateEmail();
      this.validatePassword();

      if (this.emailError || this.passwordError) {
        return;
      }

      this.isSubmitting = true;
      axios.post('http://localhost:5000/user/login', {
        email: this.email,
        password: this.password,
      })
      .then(response => {
        if (response.data.message === 'success') {
          const token = response.data.token;
          sessionStorage.setItem('jwt_token', token); 

          // 获取用户角色信息
          const isAdmin = response.data.is_admin;
          const status = response.data.status;

          if (status === false) {
            this.$message.error('您的账户已被禁用');
            return;
          }

          // 判断是否为正确的角色
          if (this.userType === 'admin' && !isAdmin) {
            this.$message.error('该账号不是管理员');
            return;
          }

          if (this.userType === 'user' && isAdmin) {
            this.$message.error('该账号不是普通用户');
            return;
          }

          // 更新 Vuex 中的用户信息
          this.$store.commit('setUserInfo', {
            username: response.data.username,
            avatar: response.data.avatar, 
            useremail: this.email,
            isAdmin: isAdmin,  
            status: status,  
          });

          // 根据用户角色跳转到不同页面
          if (isAdmin) {
            this.$router.push('/admin');
          } else {
            this.$router.push('/chat');
          }
        } else if (response.data.message === 'User does not exist') {
          // 如果是用户不存在的错误
          this.$message.error('该邮箱没有注册，请检查邮箱地址');
        } else if (response.data.message === 'Invalid password') {
          // 如果是密码错误的错误
          this.$message.error('密码错误，请重新输入');
        } else {
          this.$message.error(response.data.message || '登录失败，请重试');
        }
      })
      .finally(() => {
        this.isSubmitting = false;
      });
    },

    goToRegister() {
      this.$router.push('/register');
    },
  },
};
</script>

<style scoped>
#background {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background-image: linear-gradient(90deg, cyan, purple);
  background-size: 400%;
  animation: myanimation 10s infinite;
}

@keyframes myanimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

#logo {
  color: aliceblue;
  font-size: 25px;
  font-weight: 800;
  text-transform: uppercase;
  position: absolute;
  top: 15%;
  left: 15%;
}

#login {
  position: absolute;
  top: 30%;
  right: 15%;
  width: 35%;
  max-width: 400px;
}

.el-card {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 15px;
  width: 100%;
}

#form {
  display: flex;
  flex-direction: column;
}

.login-title {
  font-size: 32px;
  font-weight: bold;
  color: #fff;
  text-align: left;
  margin-bottom: 20px;
  margin-left: 10px;
}

#clock {
  color: aliceblue;
  position: absolute;
  top: 70%;
  left: 15%;
  text-align: left;
}

#time {
  font-size: 100px;
}

#date {
  font-size: 35px;
}

#copyright {
  color: aliceblue;
  position: absolute;
  top: 95%;
  left: 38%;
}

.el-button {
  margin-top: 10px;
  margin-left: 0;
}

.el-input {
  margin-bottom: 10px;
}

.el-input.is-error input {
  border-color: #f56c6c;  /* 错误输入框边框颜色 */
}

.el-input.is-error .el-input__inner {
  border-color: #f56c6c;
}

.el-input__error {
  color: #f56c6c;  /* 错误信息颜色 */
  font-size: 12px;
  margin-top: 5px;
}
</style>
